package com.education.business.service.education;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.education.business.mapper.education.TestPaperQuestionInfoMapper;
import com.education.business.service.BaseService;
import com.education.common.utils.FileUtil;
import com.education.model.entity.TestPaperInfo;
import com.education.model.entity.TestPaperQuestionInfo;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;


/**
 * @author zengjintao
 * @version 1.0
 * @create_at 2020/11/21 13:26
 */
@Service
public class TestPaperQuestionInfoService extends BaseService<TestPaperQuestionInfoMapper, TestPaperQuestionInfo> {

    public boolean deleteByTestPaperInfoId(Integer testPaperInfoId) {
        LambdaQueryWrapper queryWrapper = Wrappers.lambdaQuery(TestPaperQuestionInfo.class)
                .eq(TestPaperQuestionInfo::getTestPaperInfoId, testPaperInfoId);
        return super.remove(queryWrapper);
    }


    /**
     * 校验试卷是否关联了试题
     * @param testPaperInfoId
     * @return
     */
    public boolean hasTestPaperInfoQuestion(Integer testPaperInfoId) {
        LambdaQueryWrapper queryWrapper = Wrappers.lambdaQuery(TestPaperQuestionInfo.class)
                .eq(TestPaperQuestionInfo::getTestPaperInfoId, testPaperInfoId)
                .select(TestPaperQuestionInfo::getId).last(" limit 1");
        TestPaperQuestionInfo testPaperQuestionInfo = super.getOne(queryWrapper);
        return ObjectUtils.isNotEmpty(testPaperQuestionInfo);
    }

    /**
     * 根据考试任务查询
     * 读取并写入json文件
     * @param testPaperInfo
     * @return
     */
    public List<TestPaperQuestionInfo> TestPaperQuestionInfoByPaperId(List<TestPaperInfo> testPaperInfo){
        JSONArray testPaperArray = JSON.parseArray(JSON.toJSONString(testPaperInfo));
        List<TestPaperQuestionInfo> testPaperQuestionInfoList = new ArrayList();
        for (int i=0;i<testPaperArray.size();i++){
            JSONObject testPaper = JSONObject.parseObject(testPaperArray.getString(i));
            List<TestPaperQuestionInfo> testPaperQuestionInfo = baseMapper.TestPaperQuestionInfoById(testPaper.getInteger("id"));
            for (int j=0;j<testPaperQuestionInfo.size();j++) {
                testPaperQuestionInfoList.add(testPaperQuestionInfo.get(j));
            }
        }
        FileUtil.WriteFile("testPaperQuestionInfo"+".json",FileUtil.tojson(testPaperQuestionInfoList));
        return testPaperQuestionInfoList;
    }
    public int saveAll(TestPaperQuestionInfo testPaperQuestionInfo){
        return baseMapper.saveAll(testPaperQuestionInfo);
    }
}
